package main

import (
	"net/http"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"

	"myutils/models"
	"myutils/utils"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.LoadHTMLGlob("templates/*")
	r.Static("/static", "./static")

	db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	db.AutoMigrate(&models.Product{})

	// 初始化虚拟数据（600 条）
	var count int64
	db.Model(&models.Product{}).Count(&count)
	if count < 600 {
		db.Exec("DELETE FROM products") // 确保重新生成
		for i := 1; i <= 600; i++ {
			db.Create(&models.Product{
				Name:  "产品 " + utils.IntToStr(i),
				Price: 100 + i,
			})
		}
	}

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	r.GET("/api/products", func(c *gin.Context) {
		var params utils.PaginationParams
		if err := c.ShouldBindQuery(&params); err != nil {
			params = utils.PaginationParams{Page: 1, PageSize: 10}
		}
		utils.NormalizePagination(&params)

		var products []models.Product
		result, err := utils.Paginate(db, &params, &models.Product{}, &products)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, result)
	})

	r.Run(":8080")
}
